package cn.smbms.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.smbms.service.user.UserService;

import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
	private Logger logger = Logger.getLogger(UserController.class);
	
	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;

	//分页查询

	@RequestMapping(value = "/userlist.html")
	public String getUserList(Model model, @RequestParam(value = "queryname", required = false) String queryUserName,
							  @RequestParam(value = "queryUserRole", required = false) String queryUserRole,
							  @RequestParam(value = "pageIndex", required = false) String pageIndex) throws Exception {
		Integer userRole = 0;
		// 查询用户列表
		List<User> userList = null;
		// 设置页面容量
		Integer pageSize = Constants.pageSize;
		// 当前页码
		if(queryUserName == null){
			queryUserName = "";
		}
		Integer currentPageNo = 1;
		if (queryUserRole != null && !queryUserRole.equals("")) {
			userRole = Integer.parseInt(queryUserRole);
		}
		if (pageIndex != null) {
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (NumberFormatException e) {
				// response.sendRedirect("error.jsp");
				return "redirect:/user/syserror.html";
			}
		}
		// 总数量（表）
		System.out.println("用户名:"+queryUserName+"角色："+userRole);
		int totalCount = userService.getUserCount(queryUserName, userRole);
		System.out.println("查询userCount总记录数："+totalCount);
		// 总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);

		int totalPageCount = pages.getTotalPageCount();
			logger.info("总记录行数:"+totalPageCount);
		// 控制首页和尾页
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}
		System.out.println("用户名："+queryUserName+"用户角色"+userRole+"当前页"+currentPageNo+"记录数"+pageSize);
		userList = userService.getUserList(queryUserName, userRole, currentPageNo, pageSize);
		model.addAttribute("userList", userList);
		List<Role> roleList = null;
		roleList = roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		model.addAttribute("queryUserName", queryUserName);
		model.addAttribute("queryUserRole", queryUserRole);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		return "userlist";
	}

	@RequestMapping(value="/syserror.html")
	public String sysError(){
		return "syserror";
	}

	@RequestMapping(value="/useradd.html",method=RequestMethod.GET)
	public String addUser(@ModelAttribute("user") User user){
		return "useradd";
	}


	@RequestMapping(value="/useraddsave.html",method=RequestMethod.POST)
	public String addUserSave(User user, HttpSession session){
		user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setCreationDate(new Date());
		if(userService.add(user)){
			return "redirect:/user/userlist.html";
		}
		return "useradd";
	}

	@RequestMapping(value="/add.html",method=RequestMethod.GET)
	public String add(@ModelAttribute("user") User user){
		return "user/useradd";
	}

	@RequestMapping(value="/add.html",method=RequestMethod.POST)
	public String addSave(@Valid User user, BindingResult bindingResult, HttpSession session){
		if(bindingResult.hasErrors()){
			logger.debug("add user validated has error=============================");
			return "user/useradd";
		}
		user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		user.setCreationDate(new Date());
		if(userService.add(user)){
			return "redirect:/user/userlist.html";
		}
		return "user/useradd";
	}

	@RequestMapping(value = "/restful/{username}/{password}", method = RequestMethod.POST
			,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String,Object> restful(@PathVariable String username, @PathVariable String password) {
		logger.info(username+":"+password);
		Map<String, Object> returnMap = new HashMap<>(16);
		returnMap.put("username", username);
		returnMap.put("password", password);
		logger.info(JSONObject.toJSONString(returnMap));
		return returnMap;
	}

	
}
